package com.android.qos;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity {

    private static String LOG_TAG = "main";
    Button but1, but2, but3, but4;
    TextView tv1, tv2, tv3, tv4;
    
    public static final String PREFS_SERVER = "MyServer";
    String serverIP = "10.4.65.59";
    String serverPort = "80";
    String serverURL = "";
    String requestNum = "";
    String updateNum = "";
    
    private PushService pushService;
    
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(LOG_TAG, "service connected");
            pushService = ((PushService.PushBinder)service).getService();
     
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            pushService = null;
        }
        
    };
    
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateUI(intent);       
        }
    };   
    
    private void updateUI(Intent intent) {
        String status = intent.getStringExtra("status"); 
        String request = intent.getStringExtra("request");
        String update = intent.getStringExtra("update");

        tv1.setText(status);
        tv3.setText(request);
        tv4.setText(update);
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        

        
        tv1 = (TextView)findViewById(R.id.status);
        tv2 = (TextView)findViewById(R.id.ipaddr);
        tv3 = (TextView)findViewById(R.id.requestNum);
        tv4 = (TextView)findViewById(R.id.updateNum);  
        
        but1 = (Button)findViewById(R.id.connect);

        but2 = (Button)findViewById(R.id.myip);
        
        but3 = (Button)findViewById(R.id.request);


    }

    protected void onStart() {
        super.onStart();
        
        SharedPreferences serverSetting = getSharedPreferences(PREFS_SERVER, 0);
        String MyIP = serverSetting.getString("IP", serverIP);
        String MyPort = serverSetting.getString("Port", serverPort);
        
        serverURL = "http://"+MyIP+":"+MyPort;
        Intent intent = new Intent(MainActivity.this, PushService.class);
        intent.putExtra("serverUrl", serverURL);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);  
        //Auto start to service to connect server
   

        /* 
         * Get current IP address
         * 1. Listen to Button event;
         * 2. Instantiate InetAddres object, call method: getAddress()
         * 3. Set the return value to text view.
         */
        but2.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                new MyAddress().execute();
            }
        });
        
        /*
         * client send request to server
         * 1. Parse the server's response
         * 2. Send the message
         */
        but3.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                pushService.sendRequest();

            }
        });
        
    }
    
    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver, new IntentFilter(PushService.BROADCAST_ACTION));
    }
    
    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    	switch(item.getItemId()) {
    		case R.id.menu_settings:  
    			Intent intent = new Intent(MainActivity.this, UtilActivity.class);
    			startActivity(intent);
    			break;
    			
    	    default:
    	    	break;
    	    	}
    	return true;
    }

    private class MyAddress extends AsyncTask<Void,Void,String> {
        @Override
        protected String doInBackground(Void... params) {
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface
                        .getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf
                            .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        Log.e(LOG_TAG, "IP is : "+inetAddress.getHostAddress().toString());
                        String myIp = inetAddress.getHostAddress().toString();
                        if (!inetAddress.isLoopbackAddress()&& (myIp.indexOf("::")== -1)) {
                            Log.e(LOG_TAG, "IPV4 is : "+ myIp);
                            return myIp;
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e(LOG_TAG, ex.toString());
            }
            return null;
        
        }
        
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            tv2.setText(result);
        }

    }
    

    void doUnbindService() {
        unbindService(mConnection);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }
    
}
